from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import Dict, Any

mcp = FastMCP("ABRT MCP Server")

"""
面向软件：abrt (Automatic Bug Reporting Tool)

MCP tools 列表：
1. abrt_journal_core_service - 管理 abrt-journal-core.service 服务
   用途：执行、重载和查询 abrt-journal-core.service 状态
   参数：action: str (start|stop|restart|reload|status)
   返回：统一的命令执行结果 JSON

2. abrt_oops_service - 管理 abrt-oops.service 服务
   用途：执行、重载和查询 abrt-oops.service 状态
   参数：action: str (start|stop|restart|reload|status)
   返回：统一的命令执行结果 JSON

3. abrt_pstoreoops_service - 管理 abrt-pstoreoops.service 服务
   用途：查询 abrt-pstoreoops.service 状态（一次性服务）
   参数：action: str (status)
   返回：统一的命令执行结果 JSON

4. abrt_upload_watch_service - 管理 abrt-upload-watch.service 服务
   用途：执行、重载和查询 abrt-upload-watch.service 状态
   参数：action: str (start|stop|restart|reload|status)
   返回：统一的命令执行结果 JSON

5. abrt_vmcore_service - 管理 abrt-vmcore.service 服务
   用途：执行、重载和查询 abrt-vmcore.service 状态
   参数：action: str (start|stop|restart|reload|status)
   返回：统一的命令执行结果 JSON

6. abrt_xorg_service - 管理 abrt-xorg.service 服务
   用途：执行、重载和查询 abrt-xorg.service 状态
   参数：action: str (start|stop|restart|reload|status)
   返回：统一的命令执行结果 JSON

7. abrtd_service - 管理 abrtd.service 服务
   用途：执行、重载和查询 abrtd.service 状态
   参数：action: str (start|stop|restart|reload|status)
   返回：统一的命令执行结果 JSON

所有工具返回的统一 JSON 结构：
{
  "success": bool,
  "command": str,
  "exit_code": int,
  "stdout": str,
  "stderr": str
}
"""

def run_systemctl_command(service_name: str, action: str) -> Dict[str, Any]:
    """执行 systemctl 命令并返回统一格式的结果"""
    valid_actions = ['start', 'stop', 'restart', 'reload', 'status']
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} {service_name}",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Invalid action: {action}. Must be one of {valid_actions}"
        }
    
    try:
        result = subprocess.run(
            ['systemctl', action, service_name],
            capture_output=True,
            text=True,
            timeout=30
        )
        
        return {
            "success": result.returncode == 0,
            "command": f"systemctl {action} {service_name}",
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": f"systemctl {action} {service_name}",
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out"
        }
    except Exception as e:
        return {
            "success": False,
            "command": f"systemctl {action} {service_name}",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Error executing command: {str(e)}"
        }

@mcp.tool()
def abrt_journal_core_service(action: str) -> Dict[str, Any]:
    """
    管理 abrt-journal-core.service 服务
    
    参数:
        action: 要执行的操作，可选值: start, stop, restart, reload, status
    
    返回:
        JSON 结构: {
            "success": bool, 
            "command": str,
            "exit_code": int,
            "stdout": str, 
            "stderr": str
        }
    """
    return run_systemctl_command("abrt-journal-core.service", action)

@mcp.tool()
def abrt_oops_service(action: str) -> Dict[str, Any]:
    """
    管理 abrt-oops.service 服务
    
    参数:
        action: 要执行的操作，可选值: start, stop, restart, reload, status
    
    返回:
        JSON 结构: {
            "success": bool, 
            "command": str,
            "exit_code": int,
            "stdout": str, 
            "stderr": str
        }
    """
    return run_systemctl_command("abrt-oops.service", action)

@mcp.tool()
def abrt_pstoreoops_service(action: str) -> Dict[str, Any]:
    """
    管理 abrt-pstoreoops.service 服务（一次性服务）
    
    参数:
        action: 要执行的操作，主要使用 status 查询状态
    
    返回:
        JSON 结构: {
            "success": bool, 
            "command": str,
            "exit_code": int,
            "stdout": str, 
            "stderr": str
        }
    """
    return run_systemctl_command("abrt-pstoreoops.service", action)

@mcp.tool()
def abrt_upload_watch_service(action: str) -> Dict[str, Any]:
    """
    管理 abrt-upload-watch.service 服务
    
    参数:
        action: 要执行的操作，可选值: start, stop, restart, reload, status
    
    返回:
        JSON 结构: {
            "success": bool, 
            "command": str,
            "exit_code": int,
            "stdout": str, 
            "stderr": str
        }
    """
    return run_systemctl_command("abrt-upload-watch.service", action)

@mcp.tool()
def abrt_vmcore_service(action: str) -> Dict[str, Any]:
    """
    管理 abrt-vmcore.service 服务
    
    参数:
        action: 要执行的操作，可选值: start, stop, restart, reload, status
    
    返回:
        JSON 结构: {
            "success": bool, 
            "command": str,
            "exit_code": int,
            "stdout": str, 
            "stderr": str
        }
    """
    return run_systemctl_command("abrt-vmcore.service", action)

@mcp.tool()
def abrt_xorg_service(action: str) -> Dict[str, Any]:
    """
    管理 abrt-xorg.service 服务
    
    参数:
        action: 要执行的操作，可选值: start, stop, restart, reload, status
    
    返回:
        JSON 结构: {
            "success": bool, 
            "command": str,
            "exit_code": int,
            "stdout": str, 
            "stderr": str
        }
    """
    return run_systemctl_command("abrt-xorg.service", action)

@mcp.tool()
def abrtd_service(action: str) -> Dict[str, Any]:
    """
    管理 abrtd.service 服务
    
    参数:
        action: 要执行的操作，可选值: start, stop, restart, reload, status
    
    返回:
        JSON 结构: {
            "success": bool, 
            "command": str,
            "exit_code": int,
            "stdout": str, 
            "stderr": str
        }
    """
    return run_systemctl_command("abrtd.service", action)

if __name__ == "__main__":
    mcp.run()